extern crate cc;
use bindgen;
use pkg_config;

use std::collections::HashSet;

const LIBSSH_HEADER_PATH: &str = "/usr/include/libssh/";

// https://github.com/rust-lang/rust-bindgen/issues/687

fn main() {
    if cfg!(unix) {
        pkg_config::Config::new()
            .atleast_version("0.8")
            .statik(false)
            .probe("libssh")
            .expect("dynamically linked libssh >= 0.8 is required");
    } else {
        // use vcpkg
        vcpkg::Config::new()
            .emit_includes(false)
            .find_package("ssh")
            .unwrap();
    }
    generate_bindings_from_header("libssh");
    generate_bindings_from_header("server");
    generate_bindings_from_header("callbacks");
}

fn generate_bindings_from_header(name: &str) {
    let ignored_macros = IgnoreMacros(
        vec![
            "FP_INFINITE".into(),
            "FP_NAN".into(),
            "FP_NORMAL".into(),
            "FP_SUBNORMAL".into(),
            "FP_ZERO".into(),
            "IPPORT_RESERVED".into(),
        ]
        .into_iter()
        .collect::<HashSet<String>>(),
    );
    let bindings = bindgen::Builder::default()
        .header(LIBSSH_HEADER_PATH.to_owned() + name + ".h")
        .parse_callbacks(Box::new(ignored_macros))
        .rustfmt_bindings(true)
        .generate()
        .expect("Unable to generate bindings");
    bindings
        .write_to_file("./src/".to_owned() + name + ".rs")
        .expect("Couldn't write bindings!");
}

#[derive(Debug)]
struct IgnoreMacros(HashSet<String>);

impl bindgen::callbacks::ParseCallbacks for IgnoreMacros {
    fn will_parse_macro(&self, name: &str) -> bindgen::callbacks::MacroParsingBehavior {
        if self.0.contains(name) {
            bindgen::callbacks::MacroParsingBehavior::Ignore
        } else {
            bindgen::callbacks::MacroParsingBehavior::Default
        }
    }
}
